<?php

namespace app\admin\controller\mall;

use app\admin\traits\Curd;
use app\common\controller\AdminController;
use app\common\model\MallOrder;
use EasyAdmin\annotation\ControllerAnnotation;
use EasyAdmin\annotation\NodeAnotation;
use think\App;
/**
 * @ControllerAnnotation(title="销售排行")
 */
class Userseller extends AdminController
{
    use Curd;
    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->model =(new MallOrder());
    }


    /**
     * @NodeAnotation(title="列表")
     */
    public function index()
    {
        if ($this->request->isAjax()) {
            if (input('selectFields')) {
                return $this->selectList();
            }
            list($page, $limit, $where) = $this->buildTableParames();
            $count = $this->model->alias('o')
                ->field('o.openid')
                ->join('mall_user u','u.openid=o.openid')
                ->where($where)
                ->group('o.openid')
                ->count();
            $list = $this->model->alias('o')
                ->field('o.openid,u.id,u.nickName,u.mobile')
                ->join('mall_user u','u.openid=o.openid')
                ->where($where)
                ->page($page, $limit)
                ->order($this->sort)
                ->group('o.openid')
                ->select();

            foreach ($list as $kv=>$v){
                $where[] =[['openid','=',$v['openid']]];
                $totalprice =0;
                $costprice =0;
                $goodsnum =0;
                $uorders =$this->model->where($where)->select()->toArray();
                foreach ($uorders as $kk=>$vv){
                    $totalprice+=$vv['payprice'];
                    $costprice+=$vv['cost_price'];
                    $goodsnum+=$vv['goods_num'];
                }
                $list[$kv]['payprice'] =round($totalprice,2);
                $list[$kv]['costprice'] =round($costprice,2);
                $list[$kv]['goodsnum'] =$goodsnum;
            }
            $data = [
                'code'  => 0,
                'msg'   => '',
                'count' => $count,
                'data'  => $list,
            ];
            return json($data);
        }
        return $this->fetch();
    }
}